package main

import (
	"flag"
	"gitee.com/ha666/gen_sqlx_code/app"
	"gitee.com/ha666/gen_sqlx_code/gen_mssql"
	"gitee.com/ha666/gen_sqlx_code/gen_mysql"
	"github.com/Unknwon/goconfig"
	"log"
	"os/exec"
	"runtime"
	"strings"
)

const version = "2018.1113.1402"

func main() {

	//region 输出当前版本
	log.Printf("当前版本:%s\tgo版本:%s\n", version, runtime.Version())
	//endregion

	//region 判断是否安装go开发环境
	os_name := runtime.GOOS
	switch os_name {
	case "darwin", "linux":
		{
			cmd := exec.Command("sh", "-c", "go version")
			content, err := cmd.Output()
			if err != nil {
				log.Fatalf("【main】执行go version结果出错:%s\n", err.Error())
			}
			if !strings.Contains(string(content), "go version") {
				log.Fatal("【main】未安装go开发环境\n")
			}
		}
	case "windows":
		{
			content, err := exec.Command("cmd", "/c", `go version`).Output()
			if err != nil {
				log.Fatalf("【main】执行go version结果出错:%s\n", err.Error())
			}
			if !strings.Contains(string(content), "go version") {
				log.Fatal("【main】未安装go开发环境\n")
			}
		}
	default:
		{
			log.Fatal("【main】未知系统")
		}
	}
	//endregion

	//region 解析配置文件
	var err error
	app.Cfg, err = goconfig.LoadConfigFile("config.ini")
	if err != nil {
		log.Fatal("【main】读取配置文件失败[config.ini]")
	}
	sections := app.Cfg.GetSectionList()
	if len(sections) <= 0 {
		log.Fatal("【main】配置文件[config.ini]配置错误")
	}
	//endregion

	var t = flag.String("t", "", "数据库类型")
	var p = flag.String("p", "", "数据库信息")
	flag.Parse()

	//region 获取t参数
	dbType := ""
	if len(*t) <= 0 {
		log.Fatalf("【main】没有找到参数t")
	}
	dbType = *t
	if dbType != "mysql" && dbType != "mssql" {
		log.Fatalf("【main】不支持的参数t:%s", dbType)
	}
	//endregion

	//region 获取p参数
	dbName := ""
	if len(*p) <= 0 {
		log.Fatalf("【main】没有找到参数p")
	}
	is_exist := false
	for _, section := range sections {
		if section == *p {
			dbName = section
			is_exist = true
			break
		}
	}
	if !is_exist {
		log.Fatalf("【main】没有从配置文件中找到section:%s", *p)
	}
	//endregion

	//region 执行生成任务
	switch dbType {
	case "mysql":
		gen_mysql.Gen(dbName)
	case "mssql":
		gen_mssql.Gen(dbName)
	}
	//endregion

	log.Println("顺利完成")
}
